#include "downloadimage.h"
#include "ui_downloadimage.h"
#include<QNetworkRequest>
#include<QNetworkReply>
#include<QFile>
#include <QTimer>
DownloadImage::DownloadImage(QWidget *parent) :
    QWidget(parent)
{
    //网络载体
//    networkAccessManager = new QNetworkAccessManager(this);

    //网络载体的响应接收信号，与响应接收槽绑定
//    connect(networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(deal(QNetworkReply*)));
}

DownloadImage::~DownloadImage()
{
}

void DownloadImage::startDownload(QString url, QString localPathImage)
{

        qDebug() << url << "    " << localPathImage;
        QFile file;
        file.setFileName(localPathImage);
        if(file.open(QIODevice::WriteOnly))
        {
            QByteArray byte = DownloadImage::InitGetRequest(url, localPathImage);
            file.write(byte);
            this->isSuccess=true;
            file.close();
        }
        else{
            this->isSuccess=false;
        }
}

QByteArray DownloadImage::InitGetRequest(QString url, QString obj)
{
    //循环拼接
    QString baseUrl =url;
    //构造请求
    QNetworkRequest request;
    request.setUrl(QUrl(baseUrl));
    QNetworkAccessManager *manager = new QNetworkAccessManager();
    // 发送请求
    QNetworkReply *pReplay = manager->get(request);
    //开启一个局部的事件循环，等待响应结束，退出
    QEventLoop eventLoop;
    QObject::connect(pReplay,SIGNAL(finished()), &eventLoop, SLOT(quit()));

    //add timeout deal
    QTimer *tmpTimer = new QTimer();
    QObject::connect(tmpTimer,SIGNAL(timeout()),&eventLoop, SLOT(quit()));
    tmpTimer->setSingleShot(true);
    tmpTimer->start(50000);
    eventLoop.exec();
    tmpTimer->stop();

    //
    if (pReplay->error() == QNetworkReply::NoError)
    {
        qInfo() << QString("request %1 NoError").arg(localPathImage);

    }
    else
    {
        qWarning()<<QString("request %1 handle errors here").arg(obj);
        QVariant statusCodeV = pReplay->attribute(QNetworkRequest::HttpStatusCodeAttribute);
        //statusCodeV是HTTP服务器的相应码，reply->error()是Qt定义的错误码，可以参考QT的文档
        qWarning()<<QString("request %1 found error ....code: %2 %3").arg(obj).arg(statusCodeV.toInt()).arg((int)pReplay->error());
        qWarning(qPrintable(pReplay->errorString()));
    }

    //
    //获取响应信息
    QByteArray bytes = pReplay->readAll();
    return bytes;
}

